﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pixeldyne.Core.FileSystem
{
	public class FileSystem
	{
		/// <summary>
		/// Recursively runs the specified function in a directory.
		/// </summary>
		/// <param name="directory">The directory.</param>
		/// <param name="function">The function. Input parameter: <see cref="FileInfo"/>, output: <see cref="int"/>. The output return should be used
		/// as a count of files that were processed.</param>
		/// <returns>Total number of files processed.</returns>
		public int RecursiveFileFunction(string directory, Func<FileInfo, int> function)
		{
			return RecursiveFileFunction(directory, "*", function);
		}

		/// <summary>
		/// Recursively runs the specified function in a directory.
		/// </summary>
		/// <param name="directory">The directory.</param>
		/// <param name="filePattern">The file pattern.</param>
		/// <param name="function">The function. Input parameter: <see cref="FileInfo"/>, output: <see cref="int"/>. The output return should be used
		/// as a count of files that were processed.</param>
		/// <returns>Total number of files processed.</returns>
		/// <remarks></remarks>
		public int RecursiveFileFunction(string directory, string filePattern, Func<FileInfo, int> function)
		{
			if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentNullException("directory");
			if (string.IsNullOrWhiteSpace(filePattern)) throw new ArgumentNullException("filePattern");

			var i = 0;

			if (!Directory.Exists(directory))
			{
				throw new DirectoryNotFoundException(directory);
			}

			var dirInfo = new DirectoryInfo(directory);

			var files = dirInfo.GetFiles(filePattern);

			foreach (var file in files)
			{
				function(file);
				i++;
			}

			i += dirInfo.GetDirectories().Sum(dir => RecursiveFileFunction(dir.FullName, filePattern, function));

			return i;
		}
	}
}
